import { state } from '@angular/animations';
import { Actions } from '@ngrx/effects';
import { createReducer, on } from '@ngrx/store';
import { Action } from '@ngrx/store';
import { UtilsService } from '../../service/utils.service';
import * as actionType from './cart.action';
export interface CartItem {
  id: number;
  title: string;
  imageUrl: string;
  price: number;
  count: number;
  selected: boolean;
}

export interface State {
  cartList: CartItem[];
}

export const initialState: State = {
  cartList: [
    {
      id: 26,
      title: '群县眼得志步文之教',
      price: 83,
      imageUrl:
        'https://img.alicdn.com/imgextra/i3/1659066935/O1CN01vYOKNC216HOyIuWyg_!!0-item_pic.jpg_120x120q50s150.jpg',
      count: 7,
      selected: false,
    },
  ],
};

const scoreboardReducer = createReducer(
  initialState,
  on(actionType.productAdd, (state, { cartItem }) => {
    const { cartList, isChange } = new UtilsService().filterCarlist(
      state.cartList,
      cartItem
    );
    let oldProduct = isChange;
    if (!oldProduct) {
      cartList.push(cartItem);
    }
    return { ...state, cartList };
  }),
  on(actionType.productSelected, (state: State, { productSelect }) => {
    const { cartList } = new UtilsService().filterCarlist(
      state.cartList,
      productSelect,
      true
    );
    return { ...state, cartList };
  }),
  on(actionType.productSelectedAll, (state: State, { selectAll }) => {
    return { ...state, cartList: selectAll };
  }),
  on(actionType.productDelete, (state: State, { index }) => {
    const cartList = [...state.cartList];
    cartList.splice(index, 1);
    return { ...state, cartList };
  })
);
export function reducer(state: State | undefined, action: Action) {
  return scoreboardReducer(state, action);
}
